package top.glkj.hms.security;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import top.glkj.hms.utils.ResultFactory;
import top.glkj.hms.utils.StaticValue;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author : xgl
 * @version : 0.0.1
 * @date :2020/11/28 1:51
 */
@Component
@Slf4j
public class UserAuthenticationEntryPointHandler implements AuthenticationEntryPoint {
    /**
     * 用户未登录返回结果
     *
     * @param request   请求
     * @param response  响应
     * @param exception 异常
     * @author xgl
     * @date 2020/11/14
     **/
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();
        log.error(exception.getMessage());
        String str = JSONObject.toJSONString(ResultFactory.isDefine(402, StaticValue.USER_IS_NOT_CERTIFIED));
        out.write(str.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
